package com.interview.communication;

import org.junit.Test;
import static org.junit.Assert.assertEquals;

/**
 * volatile + synchronized 共享变量方式的单元测试
 */
public class SharedVariableExampleTest {

    @Test
    public void testSharedVariableDemo() throws InterruptedException {
        System.out.println("===== volatile + synchronized 测试开始 =====");
        long startTime = System.currentTimeMillis();
        
        SharedVariableExample.demo();
        
        long endTime = System.currentTimeMillis();
        System.out.println("===== volatile + synchronized 测试完成，耗时: " + (endTime - startTime) + "ms =====\n");
    }

    @Test
    public void testCounterThreadSafety() throws InterruptedException {
        // 验证多线程计数的线程安全性
        System.out.println("===== 计数器线程安全性测试 =====");
        
        SharedVariableExample.Counter counter = new SharedVariableExample.Counter();
        
        // 创建5个线程，每个线程计数100次
        Thread[] threads = new Thread[5];
        for (int i = 0; i < 5; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    counter.increment();
                }
            });
        }
        
        for (Thread t : threads) {
            t.start();
        }
        
        for (Thread t : threads) {
            t.join();
        }
        
        int finalCount = counter.getCount();
        System.out.println("预期计数: 500, 实际计数: " + finalCount);
        assertEquals("计数不正确", 500, finalCount);
        System.out.println("✓ 计数器线程安全性验证通过\n");
    }
}


